package com.lovefreedom.psi.dao.impl;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.lovefreedom.psi.bean.User;
import com.lovefreedom.psi.dao.UserDao;
import com.lovefreedom.psi.util.HibernateSessionFactory;

public class UserDaoImpl implements UserDao {

	@Override
	public void addUser(User user) {
		Session s = null;
		Transaction tx = null;
		try{
			s = HibernateSessionFactory.getSession();
			tx = s.beginTransaction();
			s.save(user);
			tx.commit();
		}finally{
			if(s!=null)
				s.close();
		}
	}

	@Override
	public void updateUser(User user) {

		Session s = null;
		Transaction tx = null;
		try{
			s = HibernateSessionFactory.getSession();
			tx = s.beginTransaction();
			s.update(user);
			tx.commit();
		}finally{
			if(s!=null)
				s.close();
		}
	}

	@Override
	public void deleteUser(User user) {

		Session s = null;
		Transaction tx = null;
		try{
			s = HibernateSessionFactory.getSession();
			tx = s.beginTransaction();
			s.delete(user);
			tx.commit();
		}finally{
			if(s!=null)
				s.close();
		}
	}

	@Override
	public User findUserById(int id) {	

		Session s = null;
		try{
			s = HibernateSessionFactory.getSession();
			User user = (User)s.get(User.class,id);
			return user;
		}finally{
			if(s!=null)
				s.close();
		}
	}
}
